package org.nabc.generate.entity;

import lombok.extern.slf4j.Slf4j;
import org.nabc.configuration.FileConfiguration;
import org.nabc.constant.ModeConstant;
import org.nabc.constant.TypeConstant;
import org.nabc.generate.AbstractRunnableTask;
import org.nabc.support.PropertyValue;
import org.nabc.support.PropertyValues;

@Slf4j
public class MybatisPlusEntityTemplateGenerate extends AbstractRunnableTask {
    private String entityTemplate;

    @Override
    public void setParameters(FileConfiguration fileConfiguration, PropertyValues propertyValues) {
        fileTemplateData = inputFromFile("src/main/resources/template/mybatis-plus/entity/Entity.template");
        entityTemplate = fileTemplateData.substring(
                fileTemplateData.indexOf("[") + 1, fileTemplateData.indexOf("]"));

        super.setParameters(fileConfiguration, propertyValues, "entity");
    }

    @Override
    public void setModelAndType() {
        this.type = TypeConstant.ENTITY;
        this.mode = ModeConstant.MYBATIS_PLUS;
    }

    @Override
    public void generate() throws Exception {
        // 构建属性信息
        StringBuffer columnInfos = new StringBuffer();
        for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
            if (propertyValue.isPrimaryKey()) {
                columnInfos.append("@TableId(type = IdType.AUTO)\n");
            }

            columnInfos
                    .append(entityTemplate
                            .replace("#{typeName}", mapperSqlTypeToType(propertyValue.getType(), this.fileSuffix))
                            .replace("#{columnName}", propertyValue.getColumnName()))
                    .append("\n");
        }

        String entityFileData = fileTemplateData.toString()
                .replace("#{primitiveTableName}", propertyValues.getPrimitiveTableName())
                .replace("#{packageName}", fileConfiguration.getPackageName())
                .replace("#{className}", entityName)
                .replace("[" + entityTemplate + "]", columnInfos);

        outputToFile(entityFileData, filePath);
    }
}
